<?php

namespace Home\Controller;

use Think\Controller;

/**
 * @author Administrator
 *
 */
class SwooleController extends Controller
{

    const LOGIN_MYSQL_TYPE = 1;
    const LOGIN_QQ_TYPE    = 2;
    public $login_type;
    public function _initialize()
    {

        $this->login_type = self::LOGIN_QQ_TYPE;
        //本地改为使用数据库用户登录
        if (C('LOCALHOST')) {
            $this->login_type = self::LOGIN_MYSQL_TYPE;
            //需要判断是否登录
            if (ACTION_NAME == 'login' || ACTION_NAME == 'logout' || ACTION_NAME == 'register') {

            } else {
                $this->checkLogin();
            }
        }

        $this->assign('login_type', $this->login_type);

    }
    public function index()
    {
        redirect(U('layim'));
    }
    public function laychat()
    {
        $this->display();
    }

    public function laychat_login()
    {
        //保存信息
        echo '<script type="text/javascript" src="http://qzonestyle.gtimg.cn/qzone/openapi/qc_loader.js" charset="utf-8" data-callback="true"></script>';exit;
    }

    public function checkLogin()
    {
        $userid = cookie('userid');
        //没有相关session则跳转到登录页
        if (!session('userid') || $userid != session('userid')) {
            //$this->error('请登陆', U('Swoole/login'));
            redirect(U('Swoole/login'));
        }
    }

    //聊天室
    public function chat()
    {
        //$this->checkLogin();
        $this->display();
    }

    //聊天室
    public function layim()
    {
        // $this->checkLogin();

        $this->assign('username', cookie('username'));
        $this->assign('userid', cookie('userid'));
        $this->display();
    }

    //查找好友页面
    public function layimFind()
    {

        $this->display();
    }

    //获取好友列表
    public function ajax_friendList()
    {
        $page     = max(1, I('get.page', '1', 'intval'));
        $pagesize = 12;
        //获取好友
        $userid      = $ids      = session('userid');
        $friend_list = M('UserFriend')->where(array('userid' => $userid))->select();
        if ($friend_list) {
            foreach ($friend_list as $value) {
                $ids .= ',' . $value['friendid'];
            }
        }
        $map['userid'] = array('notin', $ids);
        $result        = M('User')->where($map)->field('userid, username')->page($page, $pagesize)->select();

        $user_list = array();
        if ($result) {
            foreach ($result as $key => $value) {
                $user_list[$key]['Id']       = $value['friendid'];
                $user_list[$key]['username'] = $value['username'];
                $user_list[$key]['remark']   = 'demo';
                $user_list[$key]['avatar']   = 'demo.jpg';
            }
        }
        $this->ajaxReturn($user_list);
    }

    //获取好友分组
    public function ajax_getFriendGroup()
    {
        echo '<option value="1">我的好友</option>';
        exit;
    }

    //获取界面主信息
    public function ajax_getList()
    {
        $userid = I('get.userid', 0, 'intval');
        $userid = $userid ? $userid : session('userid');

        //$this->checkLogin();
        $userinfo           = M('User')->where(array('userid' => $userid))->find();
        $userinfo['avatar'] = $userinfo['avatar'] ? $userinfo['avatar'] : 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1';
        $mine               = array(
            'username' => $userinfo['nickname'],
            'userid'   => $userinfo['userid'],
        );
        $friend = array(
            'groupname' => '码屌',
            'id'        => 1,
            'online'    => 1,
            'list'      => array(),
        );
        $return['code']   = 0;
        $return['msg']    = '';
        $return['mine']   = $mine;
        $return['friend'] = $friend;
        //$this->ajaxReturn($return, '', JSON_FORCE_OBJECT);
        echo '
         {
  "code": 0
  ,"msg": ""
  ,"data": {
    "mine": {
      "username": "' . $userinfo['nickname'] . '"
      ,"id": ' . $userid . '
      ,"status": "online"
      ,"sign": "在深邃的编码世界，做一枚轻盈的纸飞机"
      ,"avatar": "' . $userinfo['avatar'] . '"
    }
    ,"friend": [{
      "groupname": "我的好友"
      ,"id": 1
      ,"list": []
    },{
      "groupname": "在线好友"
      ,"id": 2
      ,"list": [{
        "username": "晴儿"
        ,"id": "1"
        ,"status": "online"
        ,"avatar": "http://tp1.sinaimg.cn/1571889140/180/40030060651/1"
        ,"sign": "没人在线？我陪你聊"
      }]
    }]
  }
}';
    }

    public function login()
    {
        if (IS_POST) {
            $ref_url = I('post.ref_url') ? I('post.ref_url') : U('Swoole/layim');

            $map['username'] = I('post.username');
            $map['password'] = I('post.password');
            if (!$map['username'] || !$map['password']) {
                $this->error('账号密码错误');
            }
            $info = M('User')->where($map)->find();
            if ($info) {
                cookie('username', $map['username']);
                cookie('userid', $info['userid']);
                session('userid', $info['userid']);
                //$this->error('登陆成功', $ref_url);
                redirect(U('Swoole/layim'));
            } else {
                $this->error('账号密码错误');
            }
        } else {
            $ref_url = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : '';
            $this->assign('ref_url', $ref_url);
            $this->display();
        }
    }

    public function register()
    {
        if (IS_POST) {
            $info['username'] = $info['nickname'] = I('post.username');
            $info['password'] = I('post.password');

            if (!$info['username'] || !$info['password']) {
                $this->error('账号密码不能为空');
            }
            //用户名不重复
            $exist_name = M('User')->where(array('username' => $info['username']))->find();
            if ($exist_name) {
                $this->error('该用户名已存在');
            }
            $avatar = array(
                'http://q.qlogo.cn/qqapp/101328493/B6605C474682BEED9561C63E46951146/100',
                'http://q.qlogo.cn/qqapp/101328493/C8F28A757AFB4F58B74D7B4D0DB3F378/100',
                'http://q.qlogo.cn/qqapp/101328493/00B42209F8C5B6B5C67A2C0657A0906C/100',
                'http://q.qlogo.cn/qqapp/101328493/FA9D2C4BC6CF16349CE94640B999CBFF/100',
                'http://q.qlogo.cn/qqapp/101328493/DB2AD11DAD1FB0EE2449D3137638E5BD/100',
                'http://q.qlogo.cn/qqapp/101328493/08A8FEB28BFBDED91C198F80B908A5DB/100',
                'http://q.qlogo.cn/qqapp/101328493/BF9472A29AD65A0CD64E33E22AE8ACB9/100',
                'http://q.qlogo.cn/qqapp/101328493/FBDE8FEBD0277EB897AEAFE273E2624B/100',

            );
            $info['avatar'] = $avatar[rand(0, 7)];
            $userid         = M('User')->add($info);
            if (!$userid) {
                $this->error('注册失败');
            }

            D('User')->createGroup($userid);
            //直接登陆
            cookie('userid', $userid);
            cookie('username', $info['username']);
            session('userid', $userid);
            redirect(U('Swoole/layim'));
        } else {
            $this->display();
        }
    }

    public function logout()
    {
        session(null); // 清空当前的session
        cookie(null);
        redirect(U('Swoole/layim'));
    }

    //###########新版#########

    public function bind()
    {
        $userid   = session('userid');
        $userinfo = M('User')->where(array('userid' => $userid))->find();

        //取出未读消息条数
        $unread_message_count = M('user_friend_message')->where(array('to_userid' => session('userid'), 'read' => 0))->count();
        $array                = array(
            'code'                => 0,
            'unread_message'      => '',
            'unread_notice_count' => $unread_message_count ? '新' : 0,
            'userInfo'            => array(
                'type' => 'friend' //列表类型，只支持friend和group两种
                , 'avatar' => $userinfo['avatar'] ? $userinfo['avatar'] : 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1' //好友头像
                , 'username' => $userinfo['nickname']//好友昵称
                , 'groupid' => 2//所在的分组id
                , 'id' => $userid //好友id
                , 'sign' => $userinfo['description'], //好友签名
            ),
        );
        $this->ajaxReturn($array);
    }
    public function init()
    {
        $userid = session('userid');

        $userinfo           = M('User')->where(array('userid' => $userid))->find();
        $userinfo['avatar'] = $userinfo['avatar'] ? $userinfo['avatar'] : 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1';
        $mine               = array(
            'username' => $userinfo['nickname'],
            'id'       => $userinfo['userid'],
            'sign'     => $userinfo['description'],
            'avatar'   => $userinfo['avatar'],
            'status'   => 'online',
        );
        //所有好友的信息
        $friend_list = D('User')->getFriendInfo(null, I('get.online_list'));
        //群聊
        $group_list[] = array(
            "id"        => 101,
            "groupname" => "一起PHP",
            "avatar"    => "http:\/\/www.workerman.net\/img\/workerman_logo.png",
        );
        $return['code']           = 0;
        $return['msg']            = '';
        $return['data']['mine']   = $mine;
        $return['data']['friend'] = $friend_list;
        $return['data']['group']  = $group_list;

        //$return['data']['friend'][]   = $online_friend;
        $this->ajaxReturn($return, null, JSON_UNESCAPED_UNICODE);

    }

    //保存聊天记录
    public function send_message()
    {
        if (IS_POST) {
            $message_data = I('post.data');
            $type         = $message_data['to']['type'];

            $insert_data['from_userid'] = $message_data['mine']['id'];
            $insert_data['content']     = $message_data['mine']['content'];
            $insert_data['create_time'] = NOW_TIME;
            $insert_data['type']        = $type;
            switch ($type) {
                case 'group':
                    //群聊记录
                    $insert_data['groupid'] = $message_data['to']['id'];
                    break;

                default:
                    //好友聊天
                    $insert_data['to_userid'] = $message_data['to']['id'];
                    break;
            }

            $result = M('message')->add($insert_data);
            if ($result) {
                $return['code'] = 0;
            } else {
                $return['code'] = -1;
                $return['msg']  = '系统错误';
            }
            $this->ajaxReturn($return);
        }

    }

    public function chat_log()
    {

        if (IS_POST) {
            $type     = I('get.type');
            $id       = I('get.id');
            $userid   = session('userid');
            $pagesize = 20;
            if ($type == 'group') {
                $map['type']    = 'group';
                $map['groupid'] = $id;
            } else {
                $map = "(from_userid={$id} AND to_userid={$userid}) OR (to_userid={$id} AND from_userid={$userid})";
            }
            //var_dump($page);exit;

            //分页相关
            $count     = M('message')->where($map)->count();
            $pagecount = ceil($count / $pagesize);

            //默认最后一页
            $page         = I('post.curr', $pagecount, 'intval');
            $message_list = M('message')->where($map)->page($page, $pagesize)->order('id')->select();

            if ($message_list) {
                //取出相关用户的信息
                if ($type == 'group') {

                    $user_ids = array();
                    foreach ($message_list as $value) {
                        if (!in_array($value['from_userid'], $user_ids)) {
                            $user_ids[] = $value['from_userid'];
                        }
                    }
                    $user_list = M('user')->where(array('userid' => array('in', implode(',', $user_ids))))->field('userid, username, avatar, nickname')->index('userid')->select();
                } else {
                    $user_list = M('user')->where(array('userid' => array('in', "$id, $userid")))->field('userid, username, avatar, nickname')->index('userid')->select();
                }
                foreach ($message_list as $key => $value) {
                    $message_data_detail['id']        = $value['from_userid'];
                    $message_data_detail['username']  = $user_list[$value['from_userid']]['nickname'];
                    $message_data_detail['avatar']    = $user_list[$value['from_userid']]['avatar'] ? $user_list[$value['from_userid']]['avatar'] : 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1';
                    $message_data_detail['timestamp'] = $value['create_time'] * 1000;
                    $message_data_detail['content']   = $value['content'];
                    $message_data_list[]              = $message_data_detail;
                }
            }
            $return['data']    = $message_data_list;
            $return['code']    = 0;
            $return['count']   = $count;
            $return['pagesize']= $pagesize;
            $return['nowpage'] = $page;
            $this->ajaxReturn($return);
        }
        $this->display();
    }

    public function ajax_update_sign()
    {
        if (IS_POST) {
            $update_sign = I('post.sign');
            if ($update_sign) {
                $update_data['description'] = $update_sign;
                $result                     = M('user')->where(array('userid' => session('userid')))->save($update_data);
                $return['code']             = 0;

            }
            $this->ajaxReturn($return);
        }
    }

    public function find_friend()
    {
        $this->display();
    }

    public function ajax_get_user_list()
    {
        if (IS_POST) {
            //分页相关
            $pagesize = 16;

            //排除好友
            $friend_list = M('user_friend')->where(array('userid' => session('userid')))->field('friendid')->select();
            $except_user = session('userid');
            if ($friend_list) {
                foreach ($friend_list as $value) {
                    $except_user .= ',' . $value['friendid'];
                }
            }
            $map = array('userid' => array('notin', $except_user));
            //默认最后一页
            $page      = I('post.curr', 1, 'intval');
            $user_list = M('user')->where($map)->page($page, $pagesize)->field('userid, gender, avatar, nickname AS username, status')->order('status DESC,userid')->select();

            $count    = M('user')->where($map)->count();

            // if($message_list){
            //     foreach ($message_list as $key => $value) {
            //         $message_data_detail['id']          = $value['from_userid'];
            //         $message_data_detail['username']    = $user_list[$value['from_userid']]['nickname'];
            //         $message_data_detail['avatar']      = $value['avatar'] ? $value['avatar'] : 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1';
            //         $message_data_detail['timestamp']   = $value['create_time']*1000;
            //         $message_data_detail['content']     = $value['content'];
            //         $message_data_list[] = $message_data_detail;
            //     }
            // }
            $return['data']    = $user_list;
            $return['code']    = 0;
            $return['count']   = $count;
            $return['pagesize']= $pagesize;
            $return['nowpage'] = $page;
            $this->ajaxReturn($return);
        }
    }

    public function ajax_get_group_list()
    {
        $group_list     = M('user_friend_group')->where(array('userid' => session('userid')))->select();
        $return['code'] = 0;
        $return['data'] = $group_list;
        $this->ajaxReturn($return);
        // echo '[{"gid":"252","gname":"我的好友","uid":"10262"}]';
    }

    //好友申请
    public function ajax_add_friend_request()
    {
        if (IS_POST) {
            $post_data                   = I('post.data');
            $request_data['from_userid'] = session('userid');
            $request_data['content']     = $post_data['content'];
            $request_data['to_userid']   = $post_data['id'];
            $request_data['groupid']     = $post_data['groupid'];
            $request_data['create_time'] = NOW_TIME;
            //查看是否存在未同意的申请, 如果存在, 则覆盖. 拒绝的申请不覆盖
            $map['from_userid'] = session('userid');
            $map['to_userid']   = $post_data['id'];
            $map['agree']       = 0;
            $unagree_exist      = M('user_friend_message')->where($map)->find();
            if (!$unagree_exist) {
                M('user_friend_message')->add($request_data);
            } else {
                M('user_friend_message')->where($map)->save($request_data);
            }

            $return['code'] = 0;
            $this->ajaxReturn($return);
        }
    }

    //消息盒子
    public function msg_box()
    {
        $this->display();
    }

    //获取消息
    public function ajax_getMsg()
    {
        if (IS_POST) {
            $map['to_userid']    = session('userid');
            $page                = I('post.page', 1, 'intval');
            $pagesize            = 10;
            $friend_message_list = M('user_friend_message')->where($map)->order('id desc')->page($page, $pagesize)->select();
            $message_count       = M('user_friend_message')->where($map)->count();
            $pages               = ceil($message_count / $pagesize);

            //只要点开消息盒子, 则设置所有的消息为已读
            M('user_friend_message')->where($map)->save(array('read' => 1));
            if ($friend_message_list) {
                //取出发消息人的信息
                $message_from = array();
                $message_ids  = '';
                foreach ($friend_message_list as $value) {
                    $message_ids .= $message_ids ? ',' . $value['id'] : $value['id'];
                    if (!in_array($value['from_userid'], $message_from)) {
                        $message_from[] = $value['from_userid'];
                    }
                }
                //设置消息为已读
                //M('user_friend_message')->where(array('id' => array('in', $message_ids)))->save(array('read' => 1));

                $user_list  = implode(',', $message_from);
                $user_infos = M('user')->where(array('userid' => array('in', $user_list)))->field('userid, description, avatar, gender, nickname AS username')->index('userid')->select();
                foreach ($friend_message_list as $value) {
                    $message_detail = array();
                    if (!$value['from_userid']) {
                        //系统消息
                        $message_detail['time']    = date('Y-m-d', $value['create_time']);
                        $message_detail['content'] = $value['content'];
                    } else {
                        //好友申请
                        $message_detail['from']       = $value['from_userid'];
                        $message_detail['user']       = $user_infos[$value['from_userid']];
                        $message_detail['time']       = date('Y-m-d', $value['create_time']);
                        $message_detail['content']    = '申请添加好友';
                        $message_detail['remark']     = $value['content'];
                        $message_detail['from_group'] = $value['groupid'];
                        $message_detail['agree']      = (int) $value['agree'];
                    }

                    $message_list[] = $message_detail;
                }
            }
            $return['data']  = $message_list;
            $return['pages'] = $pages;
            $return['code']  = 0;
            $this->ajaxReturn($return);
        }
    }

    public function ajax_agreeFriend()
    {
        if (IS_POST) {
            $uid        = I('post.uid');
            $groupid    = I('post.group');
            $from_group = I('post.from_group');
            //不能添加自己为好友
            if ($uid == session('userid')) {
                return false;
            }
            //事务
            M()->startTrans();
            //设置user_friend_message的信息为同意
            $map_message['from_userid'] = $uid;
            $map_message['to_userid']   = session('userid');
            $result1                    = M('user_friend_message')->where($map_message)->save(array('agree' => 1));

            //添加同意消息
            $nickname                     = M('user')->where(array('userid' => session('userid')))->getfield('nickname');
            $agree_message['to_userid']   = $uid;
            $agree_message['create_time'] = NOW_TIME;
            $agree_message['content']     = $nickname . ' 已经同意你的好友申请';
            $result2                      = M('user_friend_message')->add($agree_message);

            //同意后, 添加好友到双方的好友列表中
            $mine['userid']   = session('userid');
            $mine['friendid'] = $uid;
            $mine['groupid']  = $groupid;
            $result3          = M('user_friend')->add($mine);

            $to['userid']   = $uid;
            $to['friendid'] = session('userid');
            $to['groupid']  = $from_group;
            $result4        = M('user_friend')->add($to);

            if ($result1 && $result2 && $result4 && $result4) {
                M()->commit();
                $return['code'] = 0;
            } else {
                M()->rollback();
                $return['code'] = -1;
                $return['msg']  = '系统出错';
            }
            $this->ajaxReturn($return);
        }
    }

    public function ajax_refuseFriend()
    {
        if (IS_POST) {
            $uid = I('post.uid');
            //设置user_friend_message的信息为拒绝
            $map_message['from_userid'] = $uid;
            $map_message['to_userid']   = session('userid');
            $result                     = M('user_friend_message')->where($map_message)->save(array('agree' => -1));
            if ($result) {
                $return['code'] = 0;

                //添加拒绝消息
                $nickname                     = M('user')->where(array('userid' => session('userid')))->getfield('nickname');
                $agree_message['to_userid']   = $uid;
                $agree_message['create_time'] = NOW_TIME;
                $agree_message['content']     = $nickname . '  拒绝了你的好友申请';
                M('user_friend_message')->add($agree_message);
            }
            $this->ajaxReturn($return);
        }
    }

    //变更在线状态
    public function ajax_change_status()
    {

    }

    //qq互联登录
    public function ajax_qq_login()
    {
        //判断是否存在该openid
        $openid = I('post.id');
        if (!$openid) {
            $return['code'] = -1;
            $return['msg']  = '参数错误';
        }
        $userinfo = M('user')->where(array('openid' => $openid))->find();
        if (!$userinfo) {
            //添加新用户
            $info['openid']   = $openid;
            $info['avatar']   = I('post.avatar');
            $info['nickname'] = I('post.username');
            $info['gender']   = I('post.sign');
            $userid           = M('user')->add($info);
            D('User')->createGroup($userid);
        } else {
            $userid = $userinfo['userid'];
        }
        if (!$userid) {
            $return['code'] = -1;
        } else {
            //更新用戶登錄狀態
            D('User')->where(array('userid' => $userid))->save(array('status' => 2));
        }
        $return['code'] = 0;
        //记录
        cookie('userid', $userid);
        session('userid', $userid);
        $this->ajaxReturn($return);
    }

    public function ajax_upload_img()
    {
        //临时图片
        $img_url        = 'http://img0.bdstatic.com/static/searchdetail/img/logo-2X_b99594a.png';
        $return['code'] = 0;
        $return['msg']  = '';
        $return['data'] = array('src' => $img_url);

        $this->ajaxReturn($return);
    }
    public function ajax_add_friend_group()
    {
        $groupname    = I('post.groupname');
        $gid          = D('user')->createGroup(session('userid'), $groupname);
        $group_detail = array(
            'id'        => $gid,
            'groupname' => $groupname,
            'list'      => array(),
        );
        $return['code'] = 0;
        $return['data'] = $group_detail;
        $this->ajaxReturn($return);
    }

    public function mobile_login()
    {
        $this->assign('userid', session('userid'));
        $this->display();
    }
}
